package com.nulldev.util.web.nTubeExtensions.yt_chat_on_ntube;

import java.util.Map;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.web.HttpClient.HttpClient;
import com.nulldev.util.web.HttpClient.HttpResponse;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.URLUtils.URLUtils;
import com.nulldev.util.web.flexibleKit.jfvParse.Document;
import com.nulldev.util.web.flexibleKit.jfvParse.Element;
import com.nulldev.util.web.flexibleKit.jfvParse.JFiveParse;
import com.nulldev.util.web.nTube.pages.Urlizer;

public class YTLiveChatProxifier extends HttpPage3 {

	public YTLiveChatProxifier() {
		super("/proxy/live_chat");
	}

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		final Map<String, String> s = URLUtils.parseQuery(request.url());
		if (s == null) {
			return new Response(503).requestKeepAliveDisable(true);
		}
		if (!s.containsKey("continuation")) {
			return new Response(400);
		}
		final String continuation = s.get("continuation");
		final String url = "https://www.youtube.com/live_chat?continuation=" + continuation;
		try {
			final HttpResponse<String> resp = HttpClient.getString().url(url).create();
			final String payload = resp.dataThenClose();
			final Document doc = JFiveParse.parse(payload);
			String live_chat_polymer_js = null;
			for (final Element element : doc.getElementsByTagName("script")) {
				final String src = element.getAttribute("src");
				if (src == null)
					continue;
				if (!src.endsWith("/live_chat_polymer.js"))
					continue;
				live_chat_polymer_js = src;
				break;
			}
			if (live_chat_polymer_js == null)
				return new Response(503);
			final String proxied_uri = Urlizer.urlizer(live_chat_polymer_js).replace("/proxyAPI", "/proxy/live_chat_polymer");
			return new Response(resp.status(), createStream(StringsUtil.replace(payload, live_chat_polymer_js, proxied_uri))).header("Referrer-Policy",
					"same-origin");
		} catch (Exception e) {
			JVM.errorln(e);
			return new Response(503);
		}
	}

}
